package org.twitter.connection.contator;

import java.util.List;

import org.twitter.connection.oauth.OAuth;

import twitter4j.GeoLocation;
import twitter4j.Query;
import twitter4j.QueryResult;
import twitter4j.ResponseList;
import twitter4j.Status;
import twitter4j.Tweet;
import twitter4j.Twitter;
import twitter4j.TwitterException;
import twitter4j.internal.http.HttpResponseCode;
import android.app.Activity;
import android.util.Log;

public class TwitterConator{
	private OAuth oAuth;
	private Twitter twitter;
	
	public TwitterConator(Activity activity, OAuth oAuth) throws TwitterException {
		super();
		this.oAuth = oAuth;
		this.twitter = oAuth.findTwitter();
	}

	public List<Tweet> listFindByGeoLocation(double tatitude, double longitude) throws TwitterException {
		Query query = new Query();
		query.setGeoCode(new GeoLocation(tatitude, longitude), 1, "mi");
		query.setPage(1);
		QueryResult result = twitter.search(query);
	    List <Tweet> tweets = result.getTweets();
	    return tweets;
	}
	
	public void submit(String message) throws TwitterException {
		try {
			Log.d("twitter","submit : "+message);
			twitter.updateStatus(message);
		} catch (TwitterException te) {
			errorHandler(te);
			throw te;
		}
	}
	public ResponseList<Status> listTwitter(int pageNum, int count) throws TwitterException {
		//Paging page = new Paging(pageNum, count);
		return twitter.getUserTimeline();
	}

	private void errorHandler(TwitterException te) {
		if (HttpResponseCode.FORBIDDEN == te.getStatusCode()) {
			String strError = null;
			strError = te.getErrorMessage();
			if (true == strError.contains("duplicate")) {
				Log.e("twitter","duplicate"); 
			} else if (true == strError.contains("140")) {
				Log.e("twitter","140"); 
			} else {
				Log.e("twitter","error"); 
			}
		} else if (HttpResponseCode.UNAUTHORIZED == te.getStatusCode()) {
			Log.e("twitter","UNAUTHORIZED");
		}
	}

	public void obtainCertification(String pin) {
		oAuth.obtainCertification(pin);
	}
}
